package cn.com.weshare.lock.redislock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author dujunguang
 * @description: seckill
 * @date: 2022/9/18 17:52
 * @version: 1.0.0
 **/
@RestController
public class SeckillController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/buy")
    public String buy() {
        // 锁的key值，设置成功就是拿到锁了
        String key = "buyUser";
        String value = UUID.randomUUID() + Thread.currentThread().getName();

        Boolean flagLock = stringRedisTemplate.opsForValue().setIfAbsent(key, value);
        if (Boolean.FALSE.equals(flagLock)) {
            return "get redis lock fail";
        }

        String result = stringRedisTemplate.opsForValue().get("goods:001");
        int goodsNumber = result == null ? 0 : Integer.parseInt(result);

        if (goodsNumber > 0) {
            // 模拟异常
//            int i = 1 / 0;
            int realNumber = goodsNumber - 1;
            stringRedisTemplate.opsForValue().set("goods:001", realNumber + "");
            stringRedisTemplate.delete(key);
            System.out.println("buy success，surplus：" + realNumber + "件\t" + "port：" + serverPort);
            return "buy success：" + realNumber + "\tport：" + serverPort;
        } else {
            System.out.println("sell out：" + serverPort);
        }

        return "sell out port：" + serverPort;

    }
}
